<?php
/**
 * Created by PhpStorm.
 * User: miaos
 * Date: 2015/11/3 0003
 * Time: 17:53
 */
class UserCenter_Common_UserLite {

    /**
     * 登录检测
     * @param boolean $isExitIfNotLogin 是否抛出异常以便让接口错误返回
     * @return boolean
     * @throws PhalApi_Exception_BadRequest
     */
    public function check($isExitIfNotLogin = false) {

        $uid=DI()->request->get('uid');
        $token=DI()->request->get('token');

        //是否缺少必要参数
        if (empty($uid) || empty($token)) {
            DI()->logger->debug('user not login', array('uid' => $uid, 'token' => $token));

            if ($isExitIfNotLogin) {
                throw new PhalApi_Exception_BadRequest(T('user not login'), 1);
            }
            return false;
        }

        $model = new UserCenter_Model_UserSession();
        $expiresTime = $model->getExpiresTime($uid, $token);

        //是否已过期
        if ($expiresTime <= $_SERVER['REQUEST_TIME']) {
            DI()->logger->debug('Session expired',
                array('expiresTime' => $expiresTime, 'userId' => $uid, 'token' => $token));

            if ($isExitIfNotLogin) {
                throw new PhalApi_Exception_BadRequest(T('Session expired'), 1);
            }
            return false;
        }

        return true;
    }

    /**
     * 退出登录
     */
    public function logout() {
        $this->_renewalTo($_SERVER['REQUEST_TIME']);
    }

    /**
     * 心跳
     *
     * - 自动续期
     */
    public function heatbeat() {
        $this->_renewalTo($_SERVER['REQUEST_TIME'] + UserCenter_Domain_Session::getMaxExpireTime());
    }

    /**
     * 为用户生成一个会话
     * @param int $userId 用户ID
     * @param string $client 客户端设备标识，默认为空
     * @return string 会话token，返回给客户保存，以便后续请求传递此token作登录态验证
     */
    public function generateSession($userId, $client = '') {
        return UserCenter_Domain_Session::generate($userId, $client);
    }

    /**
     * 续期
     */
    protected function _renewalTo($newExpiresTime) {
        $uid=DI()->request->get('uid');
        $token=DI()->request->get('token');
        if (empty($uid) || empty($token)) {
            return;
        }

        $model = new UserCenter_Model_UserSession();
        $model->updateExpiresTime($uid, $token, $newExpiresTime);
    }

}